package com.ruoyi.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.TimeZone;

/**
 * mybatisPlus通用字段赋值处理
 *
 * @author lie
 * @date 2022/11/21
 */
@Slf4j
@Component
public class MyMetaObjectHandle implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 转换为中国时区
        TimeZone time = TimeZone.getTimeZone("Etc/GMT-8");
        TimeZone.setDefault(time);
        Date date = new Date();
        try {
            Long userId = SecurityUtils.getLoginUser().getUserId();
            this.setFieldValByName("createTime", date, metaObject);
            this.setFieldValByName("updateTime", date, metaObject);
            this.setFieldValByName("createBy", String.valueOf(userId), metaObject);
            this.setFieldValByName("updateBy", String.valueOf(userId), metaObject);
        } catch (Exception e) {
            log.info(e.getMessage());
            this.setFieldValByName("createTime", date, metaObject);
            this.setFieldValByName("updateTime", date, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date date = new Date();
        try {
            Long userId = SecurityUtils.getLoginUser().getUserId();
            this.setFieldValByName("update_time", date, metaObject);
            this.setFieldValByName("updateBy", String.valueOf(userId), metaObject);
        } catch (Exception e) {
            log.info(e.getMessage());
            this.setFieldValByName("update_time", date, metaObject);
        }
    }
}


